// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const _data = JSON.parse(JSON.stringify(event))
  const result = {}
  const bookDb = cloud.database().collection('books').where({
    bookId: parseInt(_data.bookId)
  })
  const bookData = await bookDb.get()
  const book = bookData.data[0]
  const userId = book.owners[_data.index]
  delete book._id
  book.remain++
  book.status = true
  book.owners.splice(_data.index, 1)
  result.result1 = await bookDb.update({
    data: book
  })

  const userDb = cloud.database().collection('users').where({
    _id: parseInt(userId)
  })
  const userData = await userDb.get()
  const user = userData.data[0]
  delete user._id
  let bookIndex = null
  user.books.forEach((item, index) => {
    if (item.bookId === _data.index) {
      bookIndex = index
    }
  })
  user.books.splice(bookIndex, 1)
  user.bookCount--
  if (user.bookCount === 0) {
    user.status = 0
  }
  result.result2 = await userDb.update({
    data: user
  })
  return result
}
